# -*- coding: utf-8 -*-
import os
import sys
import time
import json
from configparser import ConfigParser

from sqlalchemy import engine_from_config
from sqlalchemy.orm import sessionmaker

sys.path.append(os.path.abspath(".."))

def _create_session(config):
    settings = {
        "sqlalchemy.url": config.get("main", "sqlalchemy.url"),
#         "sqlalchemy.pool_recycle": config.get("main", "sqlalchemy.pool_recycle"),
#         "sqlalchemy.pool_size": config.get("main", "sqlalchemy.pool_size"),
        }
    engine = engine_from_config(settings, 'sqlalchemy.')
    session = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False)()
    return session


def migrate(session, settings):
    _add_tables(session)


def _add_tables(session):
    sql = u"""CREATE TABLE `example` (
  `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
  `name` TEXT DEFAULT '',
  `notes` TEXT DEFAULT ''
  );
"""
    print("\n_add_tables ...")

    for item in sql.split(";"):
        if item.strip():
            try:
                session.execute(item)
                session.commit()
            except Exception as ex:
                print(repr(ex))
                session.rollback()
    print("Done.")


def main(argv=sys.argv):
    if len(argv) != 2:
        print("Usage: python db_migration_0.0.1.py [config_file]")
    else:
        config_file = argv[1]
        if not os.path.exists(config_file):
            print("The config file does not exist.")
        else:
            config_uri = argv[1]
            config = ConfigParser()
            config.read(config_uri)
            session = _create_session(config)
            migrate(session, config)
            session.close()


if __name__ == "__main__":
    main()
